<template>
  <a-card :bordered="false">
    <detail-list title="基本信息">
      <detail-list-item term="售后编号">{{ orderInfo.numbering }}</detail-list-item>
      <detail-list-item term="售后状态">{{ orderStatusMap[orderInfo.status] && orderStatusMap[orderInfo.status].text }}
      </detail-list-item>
      <detail-list-item term="相关订单">
        <a @click="$router.push({ name: 'order_info', params: { id: orderInfo.order_id }})">
          {{ orderInfo.order_numbering }}
        </a>
      </detail-list-item>
      <detail-list-item term="代理名称">{{ orderInfo.agent && orderInfo.agent.name }}</detail-list-item>
      <detail-list-item term="代理手机号">{{ orderInfo.agent && orderInfo.agent.phone }}</detail-list-item>
      <detail-list-item term="代理等级">{{ orderInfo.agent && levelMap[orderInfo.agent.level].text }}</detail-list-item>
      <detail-list-item term="申请时间">{{ orderInfo.created_at }}</detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="收件人信息">
      <detail-list-item term="姓名">{{ orderInfo.client && orderInfo.client.name }}</detail-list-item>
      <detail-list-item term="手机号">{{ orderInfo.client && orderInfo.client.phone }}</detail-list-item>
      <detail-list-item term="收货地址">{{ orderInfo.order && (orderInfo.order.client_address || '') }}
      </detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="发货信息">
      <OrderDelivery :show-button="false" :id="orderInfo.order_id"></OrderDelivery>
    </detail-list>

    <a-divider/>

    <detail-list title="售后信息">
      <detail-list-item term="商品名称">{{ orderInfo.order && orderInfo.order.commodity_name }}</detail-list-item>
      <detail-list-item term="活动编号">{{ orderInfo.order && orderInfo.order.commodity_activity_id }}</detail-list-item>
      <detail-list-item term="供应商">{{ orderInfo.supplier && orderInfo.supplier.name }}</detail-list-item>
      <detail-list-item term="售后类型">{{ afterSaleTypeMap[orderInfo.type] && afterSaleTypeMap[orderInfo.type].text }}
      </detail-list-item>
      <detail-list-item term="补偿款" v-if="orderInfo.type === 4">{{ orderInfo.compensation | formatAmount }}
      </detail-list-item>
      <detail-list-item term="退货款" v-if="[1, 3].includes(orderInfo.type)">{{ orderInfo.refund_amount | formatAmount }}
      </detail-list-item>
      <detail-list-item term="退运费" v-if="orderInfo.type === 1">{{ orderInfo.refund_shipping | formatAmount }}
      </detail-list-item>
      <detail-list-item term="收货地址" v-if="orderInfo.type === 2">{{ orderInfo.address || (orderInfo.client &&
        orderInfo.client.address) }}
      </detail-list-item>
      <detail-list-item :term="`${afterSaleTypeMap[orderInfo.type] && afterSaleTypeMap[orderInfo.type].reason}原因`">{{
        orderInfo.reason }}
      </detail-list-item>
      <detail-list-item term="快递公司" v-if="orderInfo.type === 1">{{ orderInfo.courier_company }}</detail-list-item>
      <detail-list-item term="退货单号" v-if="orderInfo.type === 1">{{ orderInfo.return_order_numbering }}
      </detail-list-item>
      <detail-list-item term="退货时间" v-if="orderInfo.type === 1">{{ orderInfo.return_time }}</detail-list-item>
      <detail-list-item term="凭证图片" style="z-index: 1;">
        <a-row :gutter="[56, 56]">
          <a-col
            span="8"
            v-for="att in (orderInfo.attachments && orderInfo.attachments.filter(att => att.pivot.type === 1))"
            :key="att.id"
            @click="previewImage(att.url)"
          >
            <img width="100px" :src="att.url"/>
          </a-col>
        </a-row>

        <a-modal :visible="state.picPreviewVisible" :footer="null" @cancel="state.picPreviewVisible = false">
          <img style="width: 100%" :src="picPreviewImage"/>
        </a-modal>
      </detail-list-item>
      <detail-list-item term="凭证视频" style="z-index: 1;">
        <a-row :gutter="[56, 56]">
          <a-col
            span="8"
            v-for="att in (orderInfo.attachments && orderInfo.attachments.filter(att => att.pivot.type === 2))"
            :key="att.id"
          >
            <video width="320" height="240" controls>
              <source :src="att.url" :type="att.mime_type">
              您的浏览器不支持Video标签。
            </video>
          </a-col>
        </a-row>
      </detail-list-item>
    </detail-list>

    <detail-list title="售后信息 SKU">
      <a-table
        :columns="skuColumns"
        :data-source="skuData"
        v-if="[1, 2, 3].includes(orderInfo.type)"
        :pagination="false"
      />
    </detail-list>

    <a-divider/>

    <detail-list title="处理意见">
      <a-form
        id="components-form-demo-validate-other"
        :form="form"
        @submit="handleSubmit"
        :labelCol="{ span: 3 }"
        :wrapperCol="{ span: 10 }"
      >
        <span v-if="![3, 4, 5].includes(orderInfo.status)">
          <a-form-item
            v-if="orderInfo.type === 2 && form.getFieldValue('status') === 3"
            label="快递公司"
          >
            <courier-company-selection
              v-decorator="[`courier_company_id`, { initialValue: [], rules: [{ required: true, message: '请选择快递公司' }] }]"
            />
          </a-form-item>

          <a-form-item
            v-if="orderInfo.type === 2 && form.getFieldValue('status') === 3"
            label="快递单号"
          >
            <a-input
              v-decorator="[`tracking_numbering`, { initialValue: '', rules: [{ required: true, message: '请填写快递单号' }] }]"
            />
          </a-form-item>

          <a-form-item label="审核结果">
            <a-radio-group v-decorator="['status', {rules: [{ required: true, message: '请选择审核结果' }]}]">
              <a-radio :value="3">
                审核通过
              </a-radio>
              <a-radio :value="4">
                审核未通过
              </a-radio>
              <a-radio :value="2" v-if="orderInfo.status === 1">
                跟进
              </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="意见内容">
            <a-textarea
              :row="3"
              placeholder="输入处理意见内容，选填"
              v-decorator="['audit_remarks']"
            >

            </a-textarea>
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 10, offset: 3 }">
            <a-button type="primary" html-type="submit" :loading="state.submitButtonLoading">
              提交
            </a-button>
          </a-form-item>
        </span>

        <span v-else-if="[3, 4].includes(orderInfo.status)">
          <detail-list-item term="审核结果">{{ auditResultMap[orderInfo.status].text }}</detail-list-item>
          <detail-list-item term="意见内容">{{ orderInfo.audit[0] && orderInfo.audit[0].audit_remarks }}</detail-list-item>
          <detail-list-item
            term="处理人">{{ orderInfo.audit[0] && orderInfo.audit[0].administrator.real_name }}</detail-list-item>
          <detail-list-item term="处理时间">{{ orderInfo.audit[0] && orderInfo.audit[0].created_at }}</detail-list-item>
        </span>
      </a-form>
    </detail-list>

    <!--已通过 并且 售后类型是重发货-->
    <span v-if="orderInfo.status === 3 && orderInfo.type === 2">
      <a-divider/>

      <detail-list title="重发货信息">
        <a-row :gutter="[8,8]">
          <a-col :span="8" v-for="(information, index) in orderInfo.courier_information" :key="index">
            <a-row>
              <detail-list-item term="快递公司">{{ information.courier_company.name }}</detail-list-item>
            </a-row>
            <a-row>
              <detail-list-item term="快递单号">{{ information.tracking_numbering }}</detail-list-item>
            </a-row>
          </a-col>
        </a-row>
      </detail-list>
    </span>
  </a-card>
</template>

<script>
  import DetailList from '@/components/DescriptionList/DescriptionList'
  import pick from 'lodash.pick'
  import { afterSaleOrderAudit, getAfterSaleOrderInfo } from '@/api/order'
  import { mapGetters } from 'vuex'
  import CourierCompanySelection from '@/components/CourierCompanySelection/CourierCompanySelection'
  import { formatAmount } from '@/utils/util'
  import OrderDelivery from '@/components/OrderDelivery/OrderDelivery'

  const DetailListItem = DetailList.Item

  const orderStatusMap = {
    1: {
      text: '待审核',
      icon: 'clock-o',
      iconColor: 'red',
      tips: '请耐心等待平台审核，感谢您的配合'
    },
    2: {
      text: '跟进中',
      icon: 'underway-o',
      iconColor: 'red',
      tips: '您的售后申请已由客服跟进中，请耐心等待。'
    },
    3: {
      text: '已通过',
      icon: 'checked',
      iconColor: 'green'
    },
    4: {
      text: '未通过',
      iconColor: 'red',
      icon: 'clear'
    },
    5: {
      text: '已取消',
      iconColor: 'red',
      icon: 'warning-o',
      tips: '您的售后申请已手动取消'
    }
  }

  const afterSaleTypeMap = {
    1: {
      text: '退货',
      reason: '退货'
    },
    2: {
      text: '重发货',
      reason: '重发货'
    },
    3: {
      text: '只退款',
      reason: '退款'
    },
    4: {
      text: '补偿',
      reason: '补偿'
    }
  }

  const auditResultMap = {
    3: {
      text: '审核通过'
    },
    4: {
      text: '审核未通过'
    }
  }

  export default {
    name: 'Info',
    components: { OrderDelivery, CourierCompanySelection, DetailList, DetailListItem },
    computed: {
      ...mapGetters(['levelMap'])
    },
    created () {
      getAfterSaleOrderInfo(this.$route.params.id).then(res => {
        this.orderInfo = res
        this.orderInfo.client.address = [
          res.client.province && res.client.province.name || '',
          res.client.city && res.client.city.name || '',
          res.client.area && res.client.area.name || ''
        ].reduce((address, curr) => address + curr, '') + res.client.address

        // 整理 SKU 的表头
        this.orderInfo.after_sale_order_skus[0].sku_snapshot.values.reverse().forEach(
          sku => this.skuColumns.unshift({
            'title': sku.attribute.name,
            dataIndex: sku.attribute.id
          }))
        // 整理 SKU 数据
        this.orderInfo.after_sale_order_skus.reverse().forEach(sku => {
          // sku 系统字段
          const sysField = pick(
            sku.sku_snapshot,
            ['direct_invitation', 'elite_price', 'entry_price', 'external_guide_price',
              'group_owner_price', 'indirect_invitation', 'strongman_price', 'purchase_price']
          )
          // 格式化
          Object.keys(sysField).forEach(field => {
            sysField[field] = formatAmount(sysField[field])
          })
          sysField.amount = sku.amount
          // sku 自定义数据
          sku.sku_snapshot.values.forEach(value => {
            sysField[value.attribute_id] = value.content
          })

          this.skuData.push(sysField)
        })
      })
    },
    data () {
      return {
        orderInfo: {},
        orderStatusMap: orderStatusMap,
        afterSaleTypeMap: afterSaleTypeMap,
        form: this.$form.createForm(this),
        state: {
          submitButtonLoading: false,
          picPreviewVisible: false
        },
        picPreviewImage: '',
        auditResultMap: auditResultMap,
        skuColumns: [
          {
            title: '进价（元）',
            dataIndex: 'purchase_price'
          },
          {
            title: '大咖价（元）',
            dataIndex: 'strongman_price'
          },
          {
            title: '精英价（元）',
            dataIndex: 'elite_price'
          },
          {
            title: '群主价（元）',
            dataIndex: 'group_owner_price'
          },
          {
            title: '直接奖励（元）',
            dataIndex: 'direct_invitation'
          },
          {
            title: '间接奖励（元）',
            dataIndex: 'indirect_invitation'
          },
          {
            title: '对外价格（元）',
            dataIndex: 'external_guide_price'
          },
          {
            title: '数量',
            dataIndex: 'amount'
          }
        ],
        skuData: []
      }
    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()

        this.state.submitButtonLoading = true
        this.form.validateFields((err, values) => {
          if (!err) {
            if (values.hasOwnProperty('courier_company_id')) {
              values.courier_company_id = values.courier_company_id[0]
            }
            afterSaleOrderAudit(Object.assign({ id: this.$route.params.id }, values))
              .then(res => {
                this.$message.success('操作成功!')
                this.$router.go(-1)
              })
              .finally(_ => {
                this.state.submitButtonLoading = false
              })
          } else {
            this.state.submitButtonLoading = false
          }
        })
      },
      previewImage (url) {
        this.picPreviewImage = url
        this.state.picPreviewVisible = true
      }
    }
  }
</script>

<style scoped>

</style>
